package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

// https://juejin.cn/post/6871583587062415367
func Cros() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		origin := ctx.Request.Header.Get("Origin")
		if origin == "" {
			origin = "*"
		}

		ctx.Header("Access-Control-Allow-Origin", origin)
		ctx.Header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
		ctx.Header("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Authorization,Cookie")
		ctx.Header("Access-Control-Allow-Credentials", "true")

		method := ctx.Request.Method
		if method == "OPTIONS" {
			ctx.AbortWithStatus(http.StatusNoContent)
		}

		ctx.Next()
	}
}
